package com.park.web.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.park.client.model.user.UserModel;

public class SessionUtil {
	private SessionUtil() {
	}

	public static final String GLOB_SESSION = "user";

	public static UserModel getSessionUser(HttpSession session) {
		UserModel user = (UserModel) session.getAttribute(GLOB_SESSION);
		if (user == null) {
			return null;
		}
		return user;
	}

	public static Long getUserID(HttpSession session) {
		UserModel user = (UserModel) session.getAttribute(GLOB_SESSION);
		if (user != null) {
			return user.getId();
		}
		return null;
	}

	public static UserModel getSessionUser() {
		HttpSession session = getRequest().getSession();
		if (session == null) {
			return null;
		}
		UserModel user = (UserModel) session.getAttribute(GLOB_SESSION);
		if (user == null) {
			return null;
		}
		return user;
	}

	public static Long getUserID() {
		HttpSession session = getRequest().getSession();
		if (session == null) {
			return null;
		}
		UserModel user = (UserModel) session.getAttribute(GLOB_SESSION);
		if (user != null) {
			return user.getId();
		}
		return null;
	}

	/**
	 * 获取一个request对象的方法
	 */
	private static HttpServletRequest getRequest() {
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		return attrs.getRequest();
	}

	/**
	 * 获取session 的方法
	 */
	private static HttpSession getSession() {
		return getRequest().getSession();
	}

	/**
	 * 添加到session
	 */
	public static void putUserIntoSession(UserModel user, HttpSession session) {
		session.setAttribute(GLOB_SESSION, user);
	}

	/**
	 * 添加到session
	 */
	public static UserModel putUserIntoSession(UserModel user) {
		getSession().setAttribute(GLOB_SESSION, user);
		return user;
	}

	/**
	 * 移除session
	 * @return
	 */
	public static void removeFromSession(HttpSession session) {
		UserModel userModel = (UserModel) session.getAttribute(GLOB_SESSION);
		if (userModel != null) {
			session.invalidate();
		}
	}

}
